package ru.ncedu.robot;

import java.io.File;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Foot implements Runnable {
	public final String name;
	private int position;
	
	public volatile Message msg = null;
	public volatile State state = null;
	public volatile boolean done = false; 
	
	final public Lock lock = new ReentrantLock();
	final public Condition waiting = lock.newCondition();
	
	public Foot(Head h, String name, int position){
		this.position = position;
		this.name = name;
		state = State.SLEEP;
		msg = Message.NONE;
		//System.out.println(name + " foot was created successfully! Sleeping now...");
	}

	@Override
	public void run() {
		System.out.println(name + " foot was executed!");
		setState(State.WAIT);
		while(!Thread.interrupted()){
			try {
				Message msg = getMessage();
				switch( msg){
				case FORWARD:
					setState(State.ACTIVE);
					performMoving(msg);
					done = true;
					setState(State.WAIT);
					break;
				case NONE:
					break;
				default:
					break;
				}
				
			} 
			catch (InterruptedException e) {
				break;
			}
		}
	}

	private Message getMessage() throws InterruptedException {
		lock.lock();
		try{
			while (msg == Message.NONE){
				waiting.await();
			}
			Message buf = msg;
			msg = Message.NONE;
			return buf;
		}
		finally{
			lock.unlock();
		}
	}

	private void setState(State st) {
		lock.lock();
		try{
			state = st; 
			//System.out.println(name + " going to state " + st.toString());
			if (st == State.WAIT) waiting.signal();
		}
		finally{
			lock.unlock();
		}
	}

	private void performMoving(Message msg) {
		if (msg == Message.FORWARD){
			File f = new File("damage.dat");
			if (!f.exists()){
				this.position += 5;
				System.out.format("%s foot just moved to %d.\n", this.name, this.position);
			}
			else{
				System.out.format("%s foot cann't move: it's too dangerous!\n", this.name);
			}
		}
	}

}
